package com.wxtwxt.ruralmall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.wxtwxt.ruralmall.common.to.SkuEsModel;
import com.wxtwxt.ruralmall.common.utils.R;
import com.wxtwxt.ruralmall.search.config.ElasticSearchConfig;
import com.wxtwxt.ruralmall.search.constant.EsConstant;
import com.wxtwxt.ruralmall.search.feign.ProductFeignService;
import com.wxtwxt.ruralmall.search.service.MallSearchService;
import com.wxtwxt.ruralmall.search.vo.AttrResponseVo;
import com.wxtwxt.ruralmall.search.vo.SearchParam;
import com.wxtwxt.ruralmall.search.vo.SearchResult;
import org.apache.commons.lang.StringUtils;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.NestedQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.MultiBucketsAggregation;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Wxt
 * @create 2023-04-13 9:15
 */
@Service
public class MallSearchServiceImpl implements MallSearchService {

    @Resource
    private RestHighLevelClient restHighLevelClient;
    @Resource
    private ProductFeignService productFeignService;

    @Override
    public SearchResult search(SearchParam searchParam) {
        SearchResult searchResult = null;
        // 1.准备检索请求
        SearchRequest searchRequest = buildSearchRequest(searchParam);
        // 2.执行检索请求
        try {
            SearchResponse searchResponse = restHighLevelClient.search(searchRequest, ElasticSearchConfig.COMMON_OPTIONS);
            // 3.分析响应数据封装成我们需要的格式
            searchResult = buildSearchResponse(searchResponse, searchParam);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return searchResult;
    }

    /**
     * 构造检索请求
     * @return
     */
    private SearchRequest buildSearchRequest(SearchParam searchParam) {
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        // 构造检索条件
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        if(StringUtils.isNotEmpty(searchParam.getKeyword())) {
            boolQuery.must(QueryBuilders.termQuery("skuTitle", searchParam.getKeyword()));
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.field("skuTitle");
            highlightBuilder.preTags("<b style ='color : red'>");
            highlightBuilder.postTags("</b>");
            searchSourceBuilder.highlighter(highlightBuilder);
        }
        if(searchParam.getCatelog3Id() != null) {
            boolQuery.filter(QueryBuilders.termQuery("catalogId", searchParam.getCatelog3Id()));
        }
        if(searchParam.getBrandId() != null && searchParam.getBrandId().size() > 0) {
            boolQuery.filter(QueryBuilders.termsQuery("brandId", searchParam.getBrandId()));
        }
        if(searchParam.getHasStock() != null) {
            boolQuery.filter(QueryBuilders.termQuery("hasStock", searchParam.getHasStock() == 1));
        }
        if(StringUtils.isNotEmpty(searchParam.getSkuPrice())) {
            RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("skuPrice");
            String[] prices = searchParam.getSkuPrice().split("_");
            if(prices.length == 2) {
                rangeQuery.gte(prices[0]).lte(prices[1]);
            }else {
                if(searchParam.getSkuPrice().startsWith("_")) {
                    rangeQuery.lte(prices[0]);
                }else {
                    rangeQuery.gte(prices[0]);
                }
            }
            boolQuery.filter(rangeQuery);
        }
        if(searchParam.getAttrs() != null && searchParam.getAttrs().size() > 0) {
            BoolQueryBuilder nestedBoolQuery = QueryBuilders.boolQuery();
            for (String attr : searchParam.getAttrs()) {
                String[] s = attr.split("_");
                String attrId = s[0];
                String[] attrValue = s[1].split(":");
                nestedBoolQuery.must(QueryBuilders.termQuery("attrs.attrId", attrId));
                nestedBoolQuery.must(QueryBuilders.termsQuery("attrs.attrValue", attrValue));
            }
            NestedQueryBuilder nestedQuery = QueryBuilders.nestedQuery("attrs", nestedBoolQuery, ScoreMode.None);
            boolQuery.filter(nestedQuery);
        }

        searchSourceBuilder.query(boolQuery);
        if(StringUtils.isNotEmpty(searchParam.getSort())) {
            String[] s = searchParam.getSort().split("_");
            SortOrder order = s[1].equalsIgnoreCase("asc") ? SortOrder.ASC : SortOrder.DESC;
            searchSourceBuilder.sort(s[0], order);
        }
        if(searchParam.getPageNum() != null) {
            searchSourceBuilder.from((searchParam.getPageNum() - 1) * EsConstant.PRODUCT_PAGESIZE);
        }else {
            searchSourceBuilder.from(0);
        }
        searchSourceBuilder.size(EsConstant.PRODUCT_PAGESIZE);
        TermsAggregationBuilder brandAgg = AggregationBuilders.terms("brandAgg");
        brandAgg.field("brandId")
                .size(50)
                .subAggregation(AggregationBuilders.terms("brandNameAgg").field("brandName").size(1))
                .subAggregation(AggregationBuilders.terms("brandImgAgg").field("brandImg").size(1));
        searchSourceBuilder.aggregation(brandAgg);
        TermsAggregationBuilder catalogAgg = AggregationBuilders.terms("catalogAgg");
        catalogAgg.field("catalogId").size(50);
        catalogAgg.subAggregation(AggregationBuilders.terms("catalogNameAgg").field("catalogName").size(1));
        searchSourceBuilder.aggregation(catalogAgg);
        NestedAggregationBuilder nestedAggregationBuilder = AggregationBuilders.nested("attrAgg", "attrs");
        TermsAggregationBuilder attrIdAgg = AggregationBuilders.terms("attrIdAgg").field("attrs.attrId").size(50);
        attrIdAgg.subAggregation(AggregationBuilders.terms("attrNameAgg").field("attrs.attrName").size(1));
        attrIdAgg.subAggregation(AggregationBuilders.terms("attrValueAgg").field("attrs.attrValue").size(1));
        nestedAggregationBuilder.subAggregation(attrIdAgg);
        searchSourceBuilder.aggregation(nestedAggregationBuilder);
        System.out.println("构建的DSL语句： " + searchSourceBuilder.toString());
        return new SearchRequest(new String[] {EsConstant.PRODUCT_INDEX}, searchSourceBuilder);
    }

    private SearchResult buildSearchResponse(SearchResponse searchResponse, SearchParam searchParam) {
        SearchResult searchResult = new SearchResult();
        SearchHits hits = searchResponse.getHits();
        SearchHit[] searchHits = hits.getHits();
        if(searchHits != null && searchHits.length > 0) {
            List<SkuEsModel> skuEsModels = Arrays.stream(searchHits).map(item -> {
                String sourceAsString = item.getSourceAsString();
                SkuEsModel skuEsModel = JSON.parseObject(sourceAsString, SkuEsModel.class);
                // 获取高亮信息
                if(StringUtils.isNotEmpty(searchParam.getKeyword())) {
                    HighlightField highlightField = item.getHighlightFields().get("skuTitle");
                    String skuTitle = highlightField.getFragments()[0].string();
                    skuEsModel.setSkuTitle(skuTitle);
                }
                return skuEsModel;
            }).collect(Collectors.toList());
            searchResult.setSkuEsModelList(skuEsModels);
        }
        Aggregations aggregations = searchResponse.getAggregations();
        ParsedLongTerms brandAgg = aggregations.get("brandAgg");
        List<? extends Terms.Bucket> buckets = brandAgg.getBuckets();
        if(buckets != null && buckets.size() > 0)  {
            List<SearchResult.BrandVo> brandVoList = buckets.stream().map(bucket -> {
                SearchResult.BrandVo brandVo = new SearchResult.BrandVo();
                brandVo.setBrandId(Long.parseLong(bucket.getKeyAsString()));
                ParsedStringTerms brandNameAgg = bucket.getAggregations().get("brandNameAgg");
                String brandName = brandNameAgg.getBuckets().get(0).getKeyAsString();
                ParsedStringTerms brandImgAgg = bucket.getAggregations().get("brandImgAgg");
                String brandImg = brandImgAgg.getBuckets().get(0).getKeyAsString();
                brandVo.setBrandName(brandName);
                brandVo.setBrandImg(brandImg);
                return brandVo;
            }).collect(Collectors.toList());
            searchResult.setBrandVoList(brandVoList);
        }
        ParsedLongTerms catalogAgg = aggregations.get("catalogAgg");
        List<? extends Terms.Bucket> aggBuckets = catalogAgg.getBuckets();
        if(aggBuckets != null && aggBuckets.size() > 0) {
            List<SearchResult.CatalogVo> catalogVoList = aggBuckets.stream().map(aggBucket -> {
                SearchResult.CatalogVo catalogVo = new SearchResult.CatalogVo();
                catalogVo.setCatalogId(Long.parseLong(aggBucket.getKeyAsString()));
                ParsedStringTerms catalogNameAgg = aggBucket.getAggregations().get("catalogNameAgg");
                String catalogName = catalogNameAgg.getBuckets().get(0).getKeyAsString();
                catalogVo.setCatalogName(catalogName);
                return catalogVo;
            }).collect(Collectors.toList());
            searchResult.setCatalogVoList(catalogVoList);
        }
        ParsedNested attrAgg = aggregations.get("attrAgg");
        ParsedLongTerms attrIdAgg = attrAgg.getAggregations().get("attrIdAgg");
        List<? extends Terms.Bucket> attrIdAggBuckets = attrIdAgg.getBuckets();
        if(attrIdAggBuckets != null && attrIdAggBuckets.size() > 0) {
            List<SearchResult.AttrVo> attrVoList = attrIdAggBuckets.stream().map(item -> {
                SearchResult.AttrVo attrVo = new SearchResult.AttrVo();
                attrVo.setAttrId(item.getKeyAsNumber().longValue());
                ParsedStringTerms attrNameAgg = item.getAggregations().get("attrNameAgg");
                String attrName = attrNameAgg.getBuckets().get(0).getKeyAsString();
                attrVo.setAttrName(attrName);
                ParsedStringTerms attrValueAgg = item.getAggregations().get("attrValueAgg");
                List<String> attrValueList = attrValueAgg.getBuckets().stream().map(MultiBucketsAggregation.Bucket::getKeyAsString).collect(Collectors.toList());
                attrVo.setAttrValue(attrValueList);
                return attrVo;
            }).collect(Collectors.toList());
            searchResult.setAttrVoList(attrVoList);
        }
        Integer pageNum = searchParam.getPageNum();
        if(pageNum == null) {
            pageNum = 1;
        }
        searchResult.setPageNum(pageNum);
        long total = hits.getTotalHits().value;
        searchResult.setTotal(hits.getTotalHits().value);
        searchResult.setTotalPages((int) (total % pageNum == 0 ? total / pageNum : total / pageNum + 1));
        List<Integer> pageNavs = new ArrayList<>();
        for(int i = 1; i <= total; i++) {
            pageNavs.add(i);
        }
        searchResult.setPageNavs(pageNavs);
        if (searchParam.getAttrs() != null && searchParam.getAttrs().size() > 0) {
            List<SearchResult.NavVo> collect = searchParam.getAttrs().stream().map(attr -> {
                //1、分析每一个attrs传过来的参数值
                SearchResult.NavVo navVo = new SearchResult.NavVo();
                String[] s = attr.split("_");
                navVo.setNavValue(s[1]);
                R r = productFeignService.attrInfo(Long.parseLong(s[0]));
                if (r.getCode() == 0) {
                    AttrResponseVo data = r.getData("attr", new TypeReference<AttrResponseVo>() {
                    });
                    navVo.setNavName(data.getAttrName());
                } else {
                    navVo.setNavName(s[0]);
                }

                //2、取消了这个面包屑以后，我们要跳转到哪个地方，将请求的地址url里面的当前置空
                //拿到所有的查询条件，去掉当前
                String encode = null;
                try {
                    encode = URLEncoder.encode(attr,"UTF-8");
                    encode.replace("+","%20");  //浏览器对空格的编码和Java不一样，差异化处理
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                String replace = searchParam.get_queryString().replace("&attrs=" + attr, "");
                navVo.setLink("http://search.gulimall.com/list.html?" + replace);

                return navVo;
            }).collect(Collectors.toList());
            searchResult.setNavs(collect);
        }
        System.out.println(JSON.toJSONString(searchResult));
        return searchResult;
    }
}
